﻿using Caliburn.Micro;
using MusicExplorer.Common;
using MusicExplorer.Data;
using MusicExplorer.Model;
using MusicExplorer.ViewModels.Wrappers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.System;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace MusicExplorer.ViewModels
{
    public sealed class RootViewModel : Screen
    {
        public RootViewModel()
            : base()
        {
        }

        protected override void OnInitialize()
        {
            Repository.RepositoryBase.InitRepositories(Downloader.Instance);
            ServiceDatabase.InitializeDatabase();
        }

        protected override void OnViewLoaded(object view)
        {
            var navigationService = (INavigationService)IoC.Get<INavigationService>();
            navigationService.NavigateToViewModel<HomePageViewModel>(new NavigationObject()
            {
                Root = this
            });
        }

        public event EventHandler<TrackEventArgs> PlayCurrentMedia = delegate { };
        public event EventHandler<TrackEventArgs> StopCurrentMedia = delegate { };
        public void OpenMedia(Track track)
        {
            StopCurrentMedia(this, new TrackEventArgs(track));
            PlayCurrentMedia(this, new TrackEventArgs(track));
        }

        public async void SetCurrentTrackAsRead()
        {
            m_selectedTrack.Track.IsRead = true;
            await ServiceDatabase.InsertOrUpdateTrackAsync(m_selectedTrack.Track);
            SelectedTrack.NotifyOfPropertyChange("IsRead");
        }

        private TrackTileViewModel m_selectedTrack;
        public TrackTileViewModel SelectedTrack
        {
            get { return m_selectedTrack; }
            set
            {
                if(m_selectedTrack != value)
                {
                    m_selectedTrack = value;
                    NotifyOfPropertyChange(() => SelectedTrack);
                }

                if(m_selectedTrack != null)
                {
                    OpenMedia(m_selectedTrack.Track);
                    NotifyOfPropertyChange(() => CanOpenTrackUrl);
                }
            }
        }

        public async void SearchOnYoutube()
        {
            await Launcher.LaunchUriAsync(new Uri(
                string.Format(@"http://www.youtube.com/results?search_query={0}",
                m_selectedTrack.Track.Keywords)));
        }

        public bool CanOpenTrackUrl
        {
            get { return m_selectedTrack == null ? false : !string.IsNullOrEmpty(m_selectedTrack.Track.Url); }
        }

        public async void OpenTrackUrl()
        {
            await Launcher.LaunchUriAsync(new Uri(m_selectedTrack.Track.Url));
        }
    }
}
